# 编译器设置
CC = gcc
CFLAGS = -Wall -Wextra -O2 -fPIC -I./include
LDFLAGS = -shared

LDFLAGS_TOOL = -L. -lkeyparse -lm -Wl,-rpath,.
# 源文件和目标文件
SRC_DIR = src
CORE_SRCS = $(wildcard $(SRC_DIR)/core/*.c)
PREPROCESS_SRCS = $(wildcard $(SRC_DIR)/preprocess/*.c)
GROUPING_SRCS = $(wildcard $(SRC_DIR)/grouping/*.c) $(wildcard $(SRC_DIR)/grouping/heavyguardian/*.c)
MATCHING_SRCS = $(wildcard $(SRC_DIR)/matching/*.c)
GENERATION_SRCS = $(wildcard $(SRC_DIR)/generation/*.c)
TOOL_SRCS = src/tools/keyparse_tool.c

SRCS = $(CORE_SRCS) $(PREPROCESS_SRCS) $(GROUPING_SRCS) $(MATCHING_SRCS) $(GENERATION_SRCS)
OBJS = $(SRCS:.c=.o)
TOOL_OBJS = $(TOOL_SRCS:.c=.o)


# 目标
TARGET = libkeyparse.so
TOOL_TARGET = keyparse_tool
TEST_TARGET = test_csv

# 安装目录
PREFIX = /usr/local
BINDIR = $(PREFIX)/bin
LIBDIR = $(PREFIX)/lib
INCLUDEDIR = $(PREFIX)/include

# 默认目标
all: $(TARGET) $(TOOL_TARGET) $(TEST_TARGET)

# 编译共享库 - 添加 -lm
$(TARGET): $(OBJS)
	$(CC) $(LDFLAGS) -o $@ $^ -lm

# 编译命令行工具
$(TOOL_TARGET): $(TOOL_OBJS) $(TARGET)
	$(CC) -o $@ $(TOOL_OBJS) $(LDFLAGS_TOOL)
# 编译测试程序
$(TEST_TARGET): test/test_csv.c $(TARGET)
	$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_TOOL)

# 编译规则
%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<

# 清理
clean:
	rm -f $(OBJS) $(TOOL_OBJS) $(TARGET) $(TOOL_TARGET) $(TEST_TARGET)

# 安装
install: $(TARGET) $(TOOL_TARGET)
	mkdir -p $(DESTDIR)$(BINDIR)
	mkdir -p $(DESTDIR)$(LIBDIR)
	mkdir -p $(DESTDIR)$(INCLUDEDIR)
	cp $(TARGET) $(DESTDIR)$(LIBDIR)/
	cp $(TOOL_TARGET) $(DESTDIR)$(BINDIR)/
	cp include/keyparse.h $(DESTDIR)$(INCLUDEDIR)/

# 卸载
uninstall:
	rm -f $(DESTDIR)$(LIBDIR)/$(TARGET)
	rm -f $(DESTDIR)$(BINDIR)/$(TOOL_TARGET)
	rm -f $(DESTDIR)$(INCLUDEDIR)/keyparse.h

.PHONY: all clean install uninstall